package com.banksoft.cps.controller.buy;

import com.banksoft.cps.bean.BuyCompany;
import com.banksoft.cps.bean.SaleOrder;
import com.banksoft.cps.bean.common.ServiceException;
import com.banksoft.cps.bean.query.SaleOrderQuery;
import com.banksoft.cps.bean.warpper.SaleOrderWarpper;
import com.banksoft.cps.controller.ControllerConstants;
import com.banksoft.cps.service.PractitionerService;
import com.banksoft.cps.service.SaleOrderService;
import com.banksoft.cps.util.PageUtils;
import com.banksoft.cps.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by rongzhao.zhu on 2018/9/7.
 */
@Controller
@RequestMapping("/buy/saleOrder/")
public class BuySaleOrderController  extends ControllerConstants {
    @Autowired
    SaleOrderService saleOrderService;

    @RequestMapping(value = "list", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String list(SaleOrderQuery query){
        BuyCompany buyCompany = (BuyCompany) UserContext.getUser();
        query.setBuyCompanyId(buyCompany.getId());
        List<SaleOrderWarpper> list =  saleOrderService.listWarpper(query);
        return toJSONString(createDataTip(list));
    }
    @RequestMapping(value = "count", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String count(SaleOrderQuery query){
        BuyCompany buyCompany = (BuyCompany) UserContext.getUser();
        query.setBuyCompanyId(buyCompany.getId());
        long count =  saleOrderService.count(query);
        long pageCount = PageUtils.getPage(count,query.getSize());
        return toJSONString(createDataTip(pageCount));
    }

    @RequestMapping(value = "find",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String find(String id){
        SaleOrderWarpper saleOrder = saleOrderService.findWarpperById(id);
        return toJSONString(createDataTip(saleOrder));
    }
    @RequestMapping(value = "fillBuyAmount",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String fillBuyAmount(String saleOrderId,String buyAmount){

        try {
            SaleOrder saleOrder  = saleOrderService.findById(saleOrderId);
            saleOrder.setBuyAmount(buyAmount);
            saleOrderService.save(saleOrder);
        } catch (ServiceException e) {
            return toExceptionString(e);
        }
        return toJSONString(SUCCESS);
    }
}
